package com.cwf.security.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JwtUtil {
    private static final String key = "ADwdlkmdDMKS1";


    /**
     * 生成token
     * @param map 存放的数据
     * @return 返回token header.payload.sing
     */
    public static String getToken(Map<String, Object> map) {


        Calendar instance = Calendar.getInstance();
        //默认七天过期
        instance.add(Calendar.DATE, 7);
        JWTCreator.Builder builder = JWT.create();
        //数据
        builder.withClaim("userInfo",map);
        //指定过期时间
        return builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(key));
    }

    /**
     * 验证token合法性
     * @param token 需要验证的token
     */
    public static boolean verify(String token) {
        try {
            DecodedJWT verify = JWT.require(Algorithm.HMAC256(key)).build().verify(token);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 获取token信息
     * @param token 需要获取token的信息
     * @return map的方式返回payload里面的数据
     */
    public static Map<String,Object> getTokenInfo(String token) {
        try {


            Algorithm algorithm = Algorithm.HMAC256(key);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);

            Claim userInfo = jwt.getClaim("userInfo");

            Map<String, Object> res = userInfo.asMap();

            res.put("outTime",jwt.getExpiresAt().getTime());

            System.out.println("过期时间"+jwt.getExpiresAt());


            return res;
        } catch (Exception e) {
            //e.printStackTrace();
            System.out.println("解析异常");
            return null;
        }
    }
}

